package com.heima.kafka.sample;


import org.apache.kafka.clients.producer.*;

import java.util.Properties;
import java.util.concurrent.ExecutionException;

public class ProducerQuickStart {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //2.编写配置信息
        Properties properties = new Properties();
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,"192.168.200.130:9092");
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer");
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer");
        properties.put(ProducerConfig.RETRY_BACKOFF_MS_CONFIG,10);//重试机制,每隔100ms再重试发送一下消息
        properties.put(ProducerConfig.COMPRESSION_TYPE_CONFIG,"gzip");//配置压缩机制
        //1.新建一个生产者
        KafkaProducer<String, String> producer = new KafkaProducer<String, String>(properties);
        ProducerRecord<String, String> record=new ProducerRecord<>("itcast-topic-input","hello world,hello itcast");
        //发送消息,  .get就可以拿到一个发送消息的对象,可以使用他的offset方法,拿到偏移量(同步发送,需要等待消息发送完成后才能返回offset)
        /*RecordMetadata recordMetadata = producer.send(record).get();
        System.out.println(recordMetadata.offset());*/

        //异步发送
        producer.send(record, new Callback() {
            @Override
            public void onCompletion(RecordMetadata recordMetadata, Exception e) {
                if (null!=e){
                    e.printStackTrace();
                }
                System.out.println("recordMetadata.offset() = " + recordMetadata.offset());
            }
        });
        //关闭
        producer.close();
    }
}
